<?php
declare (strict_types=1);

namespace app\common\builder;

use think\facade\Event;
use think\Model;

class TableModelBase extends Model
{

    public static function all($map, $param, $hasOne, $like = [], $order = 'create_time,desc', $append = [], $filed = '*', $export = false): array
    {
        try {
            $page = $param['page'] ?? 1;
            $limit = $param['limit'] ?? 10;

            !$order && $order = 'create_time,desc';

            if(!isset($map['is_del'])){
                $map['is_del'] = 0;
            }
            $that = parent::where($map);

            if ($hasOne) {
                $that = $that->with($hasOne);
            }

            if (isset($param['times']) && $param['times']) {
                $times = explode(' - ', $param['times']);
                $that->whereBetweenTime('create_time', strtotime($times[0]), strtotime($times[1]));
            }

            if (isset($param['otherTimes']) && $param['otherTimes']) {
                foreach ($param['otherTimes'] as $k => $v) {
                    if (empty($v)) continue;
                    $decode = explode(' - ', $v);
                    $that->whereBetweenTime($k, strtotime($decode[0]), strtotime($decode[1]));
                }
            }

            foreach ($like as $v) {
                foreach ($v as $key => $vo) {
                    $that->whereLike($key, '%' . trim($vo) . '%');
                }
            }
            $order = explode(',', $order);
            if (!$export) {

                $list = $that->page(intval($page), intval($limit))->field($filed)->order($order[0], $order[1])->select();

                if (!empty($append)) {
                    $list->append($append);
                }
                return ['code' => 0, 'data' => $list, 'count' => getCount($that->fetchSql()->select())];
            } else {

                $list = $that->field($filed)->order($order[0], $order[1])->select();
                if (!empty($append)) {
                    $list->append($append);
                }
                return ['code' => 0, 'data' => $list];
            }

        } catch (\Exception $e) {
            dump($e);
            die;
            return [];
        }
    }

    public static function getSelect($s): array
    {
        $with = isset($s['with']) ? $s['with'] : '';
        return self::all($s['map'], $s['param'], $with, $s['like'], '', [], $s['filed'], true);
    }

    public static function _magic($param): array
    {
        try {

            if (isset($param['id']) && $param['id']) {
                $model = parent::update($param);
                $model->operation = 'save';
            } else {
                $model = parent::create($param);
                $model->operation = 'create';
            }

            Event::trigger('Logs', $model);

            return ['code' => 1, 'msg' => '操作成功'];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }


    /**
     * @param array $map - 查询条件，数组格式
     * @param bool $merge - 是否合并公共查询条件
     * @param string $sort - 排序
     * @param array $with - 是否关键查询
     * @return TableModelBase[]|array|\think\Collection
     * 原点 2021年12月22日10:21:58 获取所有数据
     */
    public static function getList($map = [], $merge = true, $sort = 'sort', $with = [], $field = '*')
    {
        try {

            $map = $merge ? array_merge($map, ['is_del' => 0, 'status' => 1]) : $map;

            $that = !empty($with) ? parent::with($with)->where($map) : parent::where($map);

            return $that->order($sort, 'desc')->field($field)->select();

        } catch (\Exception $e) {

            return [];

        }
    }

    /**
     * @param array $map - 查询条件，数组格式
     * @param string $field - 查询字段，默认*
     * @param int $page - 当前页
     * @param int $limit - 每页条数，默认20
     * @param bool $merge - 是否合并is_del，status等公共状态查询条件
     * @param array $with - 是否关键查询
     * @return array
     * 原点 2021年12月22日11:26:47 分页获取数据
     */
    public static function getPageList($map = [],
                                       $field = '*',
                                       $page = 1,
                                       $limit = 20,
                                       $merge = true,
                                       $with = [],
                                       $in = [],
                                       $sort = [],
                                       $like = [],
                                       $time = [], $withoutField = '', $append = [])
    {
        try {

            $map = $merge ? array_merge($map, ['is_del' => 0, 'status' => 1]) : $map;


            $that = !empty($with) ? parent::with($with)->where($map) : parent::where($map);
            if (!empty($like)) {
                $that->whereLike($like['field'], '%' . $like['keyword'] . '%');
            }
            if ($time) {
                foreach ($time as $k => $v) {
                    $times = explode(' - ', $v['value']);
                    $that->whereBetweenTime($v['key'], $times[0], $times[1]);
                }
            }
            if (!empty($in)) {
                foreach ($in as $k => $v) {
                    $that->whereIn($k, $v);
                }
            }
            if ($withoutField) {
                $that->withoutField($withoutField);
            } else {
                $that->field($field);
            }

            $that->page(intval($page), intval($limit));

            if (!$sort) {
                $that->order($merge ? 'sort' : 'create_time', 'desc');
            } else {
                $that->order($sort['key'], $sort['value']);
            }

            $list = $that->select();
            if ($append) {
                $list->append($append);
            }

            return ['code' => 1, 'msg' => 'success', 'data' => $list];

        } catch (\Exception $e) {

            return ['code' => $e->getCode(), 'msg' => $e->getMessage()];

        }
    }


}
